package yinshi.util;

import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Objects;

public final class JavaTool {

    private JavaTool() {
    }

    public static boolean isJavaIdentifier(String id) {
        if (id == null) {
            return false;
        }

        int length = id.length();
        if (length == 0) {
            return false;
        }

        char ch = id.charAt(0);
        if (!Character.isJavaIdentifierStart(ch)) {
            return false;
        }

        for (int i = 1; i < length; i++) {
            if (!Character.isJavaIdentifierPart(ch)) {
                return false;
            }
        }
        return true;
    }

    public static void checkJavaIdentifier(String id) {
        Objects.requireNonNull(id);

        if (!isJavaIdentifier(id)) {
            throw new IllegalArgumentException(id);
        }
    }
    //
    private static long lastTime = 0;

    public static long tic() {
        lastTime = System.currentTimeMillis();
        return lastTime;
    }

    public static long toc() {
        return System.currentTimeMillis() - lastTime;
    }

    public static long toc(long lastTime) {
        return System.currentTimeMillis() - lastTime;
    }
    //
    private static boolean debug = false;
    private static PrintStream out = System.out;

    public static void enableDebug() {
        debug = true;
    }

    public static void disableDebug() {
        debug = false;
    }

    public static boolean isDebug() {
        return debug;
    }

    public static void setDebugOutput(OutputStream out) {
        JavaTool.out = new PrintStream(out);
    }

    public static void debug(String msg, Object... params) {
        if (debug) {
            out.format(msg, params);
        }
    }
}
